using System.Linq;
using Lync.Widget.Library.Configuration;
using Lync.Widget.Library.Extensions;
using Lync.Widget.Library.UserService;

namespace Lync.Widget.Library.ServiceHelpers
{
    public class ActiveDirectoryFieldMapper : IActiveDirectoryFieldMapper
    {
        public IParameterParser Parser { get; set; }
        public IActiveDirectoryMappingConfiguration MappingConfiguration { get; set; }
        public ActiveDirectoryMappingConfiguration Configuration { get; set; }

        public ActiveDirectoryFieldMapper()
            : this(new ParameterParser(), ActiveDirectoryMappingConfiguration.Load())
        {
        }

        public ActiveDirectoryFieldMapper(IParameterParser parser, IActiveDirectoryMappingConfiguration mappingConfiguration)
        {
            Parser = parser;
            MappingConfiguration = mappingConfiguration;
        }


        public bool ContainsValidQueryStringParams(string query)
        {
            var items = Parser.Parse(query);

            return MappingConfiguration.Mappings.Any(m => items.Any(item => m.QuerystringParam == item.Key));
        }

        public User GetByQuery(string query, char separator = '+')
        {
            User user = null;

            var items = Parser.Parse(query, separator);

            if (items.Count > 0)
            {
                foreach (var item in items)
                {
                    var map = MappingConfiguration.Mappings.FirstOrDefault(m => m.QuerystringParam == item.Key);

                    if (map != null)
                    {
                        if (user == null)
                        {
                            user = new User();
                        }

                        user.SetPropertyValue(map.Name, item.Value.ToLower() == map.Wildcard.ToLower() 
                            ? null 
                            : item.Value);
                    }
                }

            }

            return user;
        }
    }
}